const CryptoJS = require('crypto-js');
import * as weixin from 'weixin-js-sdk'; // 引入微信JS-SDK
var lsktl = {
    cm: {
        onoff_on: 1,
        onoff_off: 2,
    },
    version: 1,
    socketurl: "",
    ws: {
        client_id: ""
    },
    mrdata: {
        user: {id: 0, aiTimes: 0}
    },
    addonVar: {
        onoff_on: 1, onoff_off: 2
    },
    jsconfig: function (params = {}) {
        var that = this;
        lsktl.sendRequest({
            apiname: "tl/jsconfig",
            data: {url: window.location.href.split('#')[0]},
            success: function (ret) {
                lsktl.loading.hide();
                if (ret.data.errcode == 9479) {
                    weixin.config({
                        debug: false,
                        appId: ret.data.cf.appId,
                        timestamp: ret.data.cf.timestamp,
                        nonceStr: ret.data.cf.nonceStr,
                        signature: ret.data.cf.signature,
                        jsApiList: ["updateAppMessageShareData", 'updateTimelineShareData', "requestMerchantTransfer"]
                    });
                    weixin.ready(function () {
                        // 自定义分享到朋友圈的内容
                        lsktl.cache.set("jsconfig", 1);
                        if (params.success) {
                            params.success();
                        }
                    });
                } else {

                }
            }
        });
    },
    wxopenid: function () {//去获得
        // var openid = lsktl.cache.get("openid");
        if (lsktl.ci.uniPlatform == 'web') {//只有web的时候 才会有。
            var url = lsktl.webhost + "/addon.php/" + lsktl.addon_name + "/pub/mpweixin_openid?backurl_xpp=" + lsktl.base64.encode(window.location.href);
            window.location.href = url;
        }
    },
    cmvar: {
        onoff_on: 1, onoff_off: 2
    },
    wxh5: function () {
        if (lsktl.ci.uniPlatform == 'web' && lsktl.ci.ua && lsktl.ci.ua.indexOf("MicroMessenger") >= 0) {
            return true;
        }
        return false;
    },
    audio: {
        stopAll: function () {
            if (lsktl.audio.context) {
                lsktl.audio.context.stop();//关闭音频
                lsktl.clock.clearAll();//关闭所有音频
            }

        },
        aulist: [],
        context: 0,
        stop: function () {
            if (lsktl.audio.context) {
                lsktl.audio.context.stop();
            }
        },
        pause: function () {
            if (lsktl.audio.context) {
                lsktl.audio.context.pause();
            }
        },
        progress: function (callback) {

        },
        play: function (ak, params) {
            if (!ak) {
                if (!lsktl.audio.context) {
                    lsktl.audio.context.play();//播放
                }
                return false;
            }
            if (!lsktl.audio.context) {//
                lsktl.audio.context = uni.createInnerAudioContext();
            }
            lsktl.audio.context.autoplay = true;
            lsktl.audio.context.obeyMuteSwitch = true;
            if (ak.indexOf("https://") >= 0) {//即是url地址
                lsktl.audio.context.src = ak;
            } else {
                lsktl.audio.context.src = lsktl.resurl + ak;
            }
            lsktl.audio.context.stop();//f
            /*  lsktl.audio.context.onCanplay(function (res) {
                  if(params.onCanplay){
                      params.onCanplay(res);
                  }
              });
              lsktl.audio.context.onTimeUpdate(function (res) {
                  if(params.onTimeUpdate){
                      params.onTimeUpdate(res);
                  }
              });*/

            lsktl.audio.context.onError(function (t) {
                lsktl.audio.context = 0;//则初始化
            });
            lsktl.audio.context.play();//
        }
    },
    base64: {
        encode: function (rawStr) {
            var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
// 将WordArray对象转换为Base64编码的字符串
            return CryptoJS.enc.Base64.stringify(wordArray);
        },
        decode: function (base64Str) {
// 将Base64字符串解析为WordArray对象
            var parsedWordArray = CryptoJS.enc.Base64.parse(base64Str);
// 将WordArray对象转换回原始字符串
            return parsedWordArray.toString(CryptoJS.enc.Utf8);
        }
    },
    // 配置服务器地址 - 用于获取动态配置
    configServerUrl: "http://192.168.10.104:3000", // 修改为实际的配置服务器地址
    webhost: "http://qm.lr12.com", // 默认值,将从配置服务器动态加载
    webviewUrl: "", // webview URL,将从配置服务器动态加载
    apiurl: "",
    resurl: "",
    addon_name: "qm", // 默认值,将从配置服务器动态加载
    configVersion: 0, // 配置版本号
    configLoaded: false, // 配置是否已加载
    clientInfo: {bsid: ""},
    bsid_client: 0,
    inwx: false,
    clock: {
        list: [],
        push: function () {

        },
        clearAll: function () {
            for (var i in lsktl.clock.list) {
                clearInterval(lsktl.clock.list[i]);
            }
        },
        clear: function (index) {
            clearInterval(lskt.clock.list[index]);//清空
        }
    },
    showToast: function (params) {
        lsktl.loading.hide();
        setTimeout(function () {
            uni.showToast(params);
        });
    },
    saveImg: function (picurl) {
        uni.downloadFile({//下载
            url: picurl, //图片下载地址
            success: res => {
                if (res.statusCode === 200) {
                    uni.saveImageToPhotosAlbum({//保存图片到系统相册。
                        filePath: res.tempFilePath,//图片文件路径
                        success: function () {
                            uni.showToast({
                                title: '图片保存成功',
                                icon: 'none',
                            });
                        },
                        fail: function (e) {
                            console.log(e);
                            uni.showToast({
                                title: '图片保存失败',
                                icon: 'none',
                            });
                        }
                    });
                }
            }
        });
    },
    navdata: {
        statusBarHeight: 0, boxHeight: 0, spaceBottom: 0
    },
    // 加载远程配置
    loadConfig: function (callback) {
        var that = this;
        // 先尝试从缓存加载配置
        var cachedConfig = lsktl.cache.get("appConfig");
        if (cachedConfig && !lsktl.empty(cachedConfig)) {
            try {
                var config = JSON.parse(cachedConfig);
                that.applyConfig(config);
                that.configLoaded = true;
                console.log("从缓存加载配置成功");
            } catch (e) {
                console.error("解析缓存配置失败:", e);
            }
        }

        // 从服务器获取最新配置
        uni.request({
            url: that.configServerUrl + "/api/config",
            method: "GET",
            success: function (res) {
                if (res.statusCode === 200 && res.data.errcode === 0) {
                    var config = res.data.data;
                    // 检查版本号,如果有更新则应用新配置
                    if (!cachedConfig || config.version > that.configVersion) {
                        that.applyConfig(config);
                        // 缓存配置
                        lsktl.cache.set("appConfig", JSON.stringify(config));
                        console.log("从服务器加载配置成功,版本:", config.version);
                    }
                    that.configLoaded = true;
                    if (callback) callback(true);
                } else {
                    console.error("获取配置失败:", res);
                    if (callback) callback(false);
                }
            },
            fail: function (err) {
                console.error("请求配置失败:", err);
                // 如果请求失败但有缓存,继续使用缓存
                if (callback) callback(cachedConfig ? true : false);
            }
        });
    },

    // 应用配置
    applyConfig: function (config) {
        if (config.webhost) {
            this.webhost = config.webhost;
        }
        if (config.webviewUrl) {
            this.webviewUrl = config.webviewUrl;
        }
        if (config.addon_name) {
            this.addon_name = config.addon_name;
        }
        if (config.version) {
            this.configVersion = config.version;
        }
        // 更新 API 和资源 URL
        this.apiurl = this.webhost + "/api.php/" + this.addon_name + "/";
        this.resurl = this.webhost + "/static/addon/" + this.addon_name + "/";
    },

    init: function () {
        lsktl.ci = uni.getSystemInfoSync();//
        lsktl.navdata.statusBarHeight = lsktl.ci.statusBarHeight;//状态栏高度
        lsktl.navdata.boxHeight = 54;
        lsktl.navdata.ttheight = 54 + lsktl.ci.statusBarHeight;
        lsktl.navdata.spaceBottom = lsktl.ci.safeAreaInsets.bottom || 0;
        if (lsktl.ci.ua && lsktl.ci.ua.indexOf("MicroMessenger") >= 0) {
            lsktl.inwx = true;
        }
        this.apiurl = this.webhost + "/api.php/" + this.addon_name + "/";
        this.resurl = this.webhost + "/static/addon/" + this.addon_name + "/";
        lsktl.bsid_client = lsktl.cache.get("bsid_client");
        if (lsktl.empty(lsktl.bsid_client)) {
            lsktl.bsid_client = lsktl.uuid();
            lsktl.cache.set("bsid_client", lsktl.bsid_client);
        }

        // 加载远程配置
        this.loadConfig();
    },
    padLeft: function (digit, fillstr) {
        fillstr = fillstr || "0";
        if (digit < 10) {
            return fillstr + digit;
        }
        return digit;
    },
    cpage: function () {
        var pagelist = getCurrentPages();
        var cp = pagelist[pagelist.length - 1];//得到当前页
        var page=cp.__page__?cp.__page__:cp.$page;
        var ra = {
            fullpath: page.fullPath,
            id: page.id,
            options: page.options,
            path: page.path,
            route: page.route,
        };
        return ra;
    },
    backurl:function(fullpath){
        if(fullpath){
            lsktl.cache.set("backurl",fullpath);
        }else{
            lsktl.cache.set("backurl",lsktl.cpage().fullpath);
        }
        console.info(lsktl.cache.get("backurl"));
    },
    empty(p1) {//判断一个对象是否为空
        if (p1 == null) {
            return true;
        }
        if (p1 == undefined) {
            return true;
        }
        switch (typeof p1) {
            case "undefined":
                return true;
                break;
            case "object":
                if (Object.keys(p1).length == 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case "number":
                return p1 == 0 ? true : false;
                break;
            case "string":
                return lsktl.trim(p1, "") == "" ? true : false;
                break;
            case "boolean":
                return p1;
                break;
            case "string":
                if (p1 == "" || p1 == "false") {
                    return true;
                } else {
                    return false;
                }
                break;
            default:
                return true;
                break;
        }
        return true;
    },
    console: {
        info: function (data) {
            console.info(typeof data);
            if (!data) {
                console.info("9479==>null");
                return false;
            }
            if (typeof data == "object" || typeof data == "Array") {
                console.info("9479==>" + JSON.stringify(data));
            } else {
                console.info("9479==>" + data);
            }
        },
    },
    url: {
        format: function (url = "") {
            var index = url.indexOf("?");
            var options = {};
            var route = url;//默认的是这个
            var query = "";
            if (index > 0) {//即大于
                query = url.substr(index + 1);
                route = url.substr(0, index);
                if (query != "") {
                    var parts = query.split("&");
                    var kv;
                    for (var i = 0; i < parts.length; i++) {
                        kv = parts[i].split("=");
                        options[kv[0]] = kv[1];
                    }
                }
            }
            route = lsktl.trim(route, "/");
            var urlpath = "/" + route;
            return {route: route, options: options, query: query, urlpath: urlpath};
        },
        get: function (url = "", key = "") {
            var fa = lsktl.url.format(url);
            var ra = fa.options[key];
            ra = undefined ? 0 : ra;
            return ra;
        },
        set: function (url, params = {}) {
            var fa = lsktl.url.format(url);
            for (var i in params) {
                fa.options[i] = params[i];
            }
            var querystr = "";
            for (var i in fa.options) {
                querystr += i + "=" + fa.options[i] + "&";
            }
            querystr = lsktl.trim(querystr, "&");
            var str = fa.urlpath + (querystr == "" ? "" : "?" + querystr);
            return str;
        }
    },
    pay: function (params) {//参数
        params.paytype = params.paytype || "";
        lsktl.sendRequest({
            url: "order/getpayinfo",
            data: {id: params.order_id, openid: params.openid || '', paytype: params.paytype},
            success: function (ret) {
                lsktl.loading.hide();
                if (ret.data.errcode == 9479) {
                    ret.data.unipayInfo.success = function (res) {
                        params.success && params.success(res);
                    }
                    ret.data.unipayInfo.complete = function (res) {
                        params.complete && params.complete(ret);
                    }
                    if (lsktl.wxh5()) {//如果是在
                        // wx.requestPayment(ret.data.payinfo);//调用微信wxapy_js支付
                        WeixinJSBridge.invoke('getBrandWCPayRequest', ret.data.jsobj,
                            function (res) {
                                if (res.err_msg.indexOf("get_brand_wcpay_request:ok") >= 0) {//即支付成功
                                    //只是支付成功了，要重新通过订单获取信息才行。
                                    params.success && params.success(res);
                                } else {
                                    //支付失败了，
                                    params.fail && params.fail(res);
                                }
                                params.complete && params.complete(res);
                            });

                    } else {
                        uni.requestPayment(ret.data.unipayInfo);//使用wxpay
                    }
                } else {
                    params.complete && params.complete(ret);
                }
                // wx.requestPayment(ret.data.payinfo);
            }
        });
    },
    gourl: function (params) {
        // return false;
        if (typeof params == "string") {//即如果是string
            params = {
                url: params
            };
        }
        if (params.url.indexOf("pages/site/index") >= 0) {//即首页
            uni.reLaunch({
                url: "/" + lsktl.trim(params.url, '/')
            });
            return false;
        }
        if (params.redirect) {
            uni.reLaunch({
                url: "/" + lsktl.trim(params.url, '/')
            });
        } else {
            uni.navigateTo({
                url: params.url
            });//跳转
        }

    },
    back: function (delta) {
        var pages = getCurrentPages();
        var len = pages.length;
        if (len === 1) {
            uni.reLaunch({
                url: "/pages/site/index"
            });
        } else {
            uni.navigateBack({
                delta: delta || 1
            });
        }

    },
    sendRequest: function (params = {}) {
        var pagelist = getCurrentPages();
        var cpage = pagelist[pagelist.length - 1];//第一页
        var cpinfo = {
            route: cpage.route || "",
            is: cpage.is || "",
            options: cpage.options || ""
        };
        var i = params.ha || {};
        i["Content-Type"] = "application/x-www-form-urlencoded";
        i.Accept = "application/json";
        var url = lsktl.apiurl + (params.apiname || params.url);
        var a = {
            data: JSON.parse(JSON.stringify(params.data))
        };
        a.data.bsid_client = lsktl.cache.get("bsid_client");
        a.data.cpinfo = JSON.stringify(cpinfo);
        a.data.bsidlogin = lsktl.cache.get("bsidlogin");
        a.data.lskuserid = lsktl.cache.get("lskuserid");
        a.data.fuid = lsktl.cache.get("fuid") || 0;
        a.data.version = lsktl.version;
        a.data.pfinfo = lsktl.base64.encode(JSON.stringify(lsktl.ci));
        wx.request({
            url: url,
            data: a.data || {},
            method: params.method || "POST",
            header: i,
            success: function (n) {
                if (n.data.errcode == 401) {
                    //则跳到登录
                    if (lsktl.wxh5()) {
                        var url = lsktl.webhost + "/addon.php/" + lsktl.addon_name + "/pub/mpweixin_openid";
                        window.location.href = url;
                    } else {
                        lsktl.gourl({
                            url: "/pages/pub/login"
                        });
                    }
                    return false;
                }
                "function" == typeof params.success && params.success(n);
            },
            fail: function (t) {
                "function" == typeof params.fail && params.fail(t);
            },
            complete: function (t) {
                lsktl.loading.hide();
                if (t.errcode == 401) {//即需要登录
                    var url = lsktl.webhost + "/addon.php/" + lsktl.addon_name + "/pub/mpweixin_openid";
                    window.location.href = url;
                    return false;
                }
                // lsktl.loading.hide();
                "function" == typeof params.complete && params.complete(t);
            }
        });
    },
    time: function () {
        return parseInt(new Date().getTime().toString().substr(0, 10));
    },//得到时间
    date: function (pa_format, pa_time) {//格式化时间
        var timestamp = pa_time || lsktl.time();//得到时间
        var dd = new Date(timestamp * 1000);
        var Y = dd.getFullYear();
        var M = (dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1);
        var D = (dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate());
        var h = (dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours());
        var m = (dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes());
        var s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds();
        var str = pa_format;
        str = str.replace(new RegExp('Y', 'g'), Y);
        str = str.replace(new RegExp('m', 'g'), M);
        str = str.replace(new RegExp('d', 'g'), D);
        str = str.replace(new RegExp('H', 'g'), h);
        str = str.replace(new RegExp('i', 'g'), m);
        str = str.replace(new RegExp('s', 'g'), s);
        console.info(str);
        return str;
    },

    rndint: function (t, e) {
        return Math.floor(Math.random() * (e - t + 1)) + t;
    },
    random_: function (t, e) {
        return (Math.random() * (e - t) + t).toFixed(2);
    },
    loading: {
        isLoading: 0,
        show: function () {
            if (lsktl.loading.isLoading) {
                return false;
            }
            wx.showLoading({title: "加载中.."});
            lsktl.loading.isLoading = 1;
        },
        hide: function () {
            wx.hideLoading();
            lsktl.loading.isLoading = 0;
        }
    },
    rtrim: function (text, char) {
        return text.replace(new RegExp('\\' + char + '+$', 'g'), '');
    },
    ltrim: function (text, char) {
        return text.replace(new RegExp('^\\' + char + '+', 'g'), '');
    },
    trim: function (text, char) {
        if (char) {
            return text.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
        } else {
            return text.replace(/^\s+|\s+$/g, '');
        }
    },
    uuid: function () {
        for (var t = [], e = 0; e < 36; e++) t[e] = "0123456789abcdef".substr(Math.floor(16 * Math.random()), 1);
        t[14] = "4", t[19] = "0123456789abcdef".substr(3 & t[19] | 8, 1), t[8] = t[13] = t[18] = t[23] = "-";
        var a = t.join("");
        return a;
    },
    cache: {
        get: function (key) {
            return wx.getStorageSync(key);
        },
        set: function (key, value) {
            wx.setStorageSync(key, value);
        },
        clear: function () {
            wx.clearStorageSync();//清除
        }
    },
    rndstr: function (p_min, p_max, p_randomFlag) {
        var str = "", min = p_min || 16, max = p_max || 32, pos = 0,
            range = min, randomFlag = p_randomFlag || false,
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        // 随机产生
        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        for (var i = 0; i < range; i++) {
            pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    }
};
lsktl.init();//初始化
module.exports = lsktl;
